package server;

import handle.MsgHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class CloudKeeperServer {
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(10055);
		} catch (IOException e) {
			e.printStackTrace();
		}

		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();

				InputStream is = socket.getInputStream();
				OutputStream os = socket.getOutputStream();

				byte[] cache = new byte[1024 * 1024];
				int total = 0;
				int length;
				byte[] buf = new byte[1024];
				while ((length = is.read(buf)) != -1) {
					for (int i = 0; i < length; i++) {
						cache[i + total] = buf[i];
					}
					total += length;
				}
				byte[] buffer = new byte[total];
				for (int i = 0; i < total; i++) {
					buffer[i] = cache[i];
				}
				MsgHandler.hander(buffer);

				os.write("return".getBytes());
				socket.shutdownOutput();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (socket != null) {
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}